﻿using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Web;

namespace Job.Core.Web.HttpModules
{
    /// <summary>
    /// 实现 Url 重写，可在 Global.asax 文件中配置重写映射。
    /// </summary>
    public class UrlRewriter : IHttpModule
    {
        #region Properties

        private static List<Regex> lookFor = new List<Regex>();

        /// <summary>
        /// 需重写的url正则。
        /// </summary>
        public static List<Regex> LookFor
        {
            get { return lookFor; }
        }

        private static List<string> sendTo = new List<string>();

        /// <summary>
        /// 需重写到的地址。
        /// </summary>
        public static List<string> SendTo
        {
            get { return UrlRewriter.sendTo; }
        }

        #endregion

        #region IHttpModule 成员

        public void Dispose()
        {
            
        }

        public void Init(HttpApplication context)
        {            
            context.BeginRequest += new EventHandler(Rewriter);
        }

        #endregion

        #region Methods

        /// <summary>
        /// 重写。
        /// </summary>
        /// <param name="sender">sender。</param>
        /// <param name="e">e。</param>
        private void Rewriter(object sender, EventArgs e)
        {
            HttpContext context = ((HttpApplication)sender).Context;            

            string sendTo = string.Empty;
            string raw = context.Request.Url.ToString();

            for (int i = 0; i < LookFor.Count; i++)
            {
                if (LookFor[i].IsMatch(raw))
                {
                    sendTo = LookFor[i].Replace(raw, SendTo[i]);
                    context.RewritePath(sendTo);                    
                    break;
                }
            }
        }
        #endregion
    }
}